// 标准化URL函数
const normalizeUrl = (url) => {
  try {
    let u = new URL(url);
    // 移除默认端口
    if ((u.protocol === 'http:' && u.port === '80') || 
        (u.protocol === 'https:' && u.port === '443')) {
      u.port = '';
    }
    // 统一协议小写
    u.protocol = u.protocol.toLowerCase();
    // 小写主机名
    u.hostname = u.hostname.toLowerCase();
    // 移除锚点和无意义参数
    u.hash = '';
    const params = new URLSearchParams(u.search);
    ['utm_source', 'utm_medium', 'fbclid'].forEach(p => params.delete(p));
    u.search = params.toString();
    return u.toString();
  } catch (e) {
    console.error("无效URL:", url);
    return null;
  }
};


// 检测重复URL
const findDuplicates = (bookmarks) => {
  try {
    // 安全检查
    if (!bookmarks || !Array.isArray(bookmarks)) {
      console.error('Invalid bookmarks data passed to findDuplicates');
      return [];
    }
    
    const urlMap = new Map();
    bookmarks.forEach(bookmark => {
      // 确保每个书签项有效且有URL属性
      if (bookmark && typeof bookmark === 'object' && bookmark.url) {
        const normUrl = normalizeUrl(bookmark.url);
        if (normUrl) {
          if (!urlMap.has(normUrl)) {
            urlMap.set(normUrl, []);
          }
          urlMap.get(normUrl).push(bookmark);
        }
      }
    });
    
    // 过滤出重复项（数量>1的组）
    return Array.from(urlMap.entries())
      .filter(([_, group]) => group.length > 1)
      .map(([normUrl, group]) => ({
        normUrl,
        bookmarks: group.sort((a,b) => b.dateAdded - a.dateAdded) // 按时间排序
      }));
  } catch (error) {
    console.error('Error in findDuplicates:', error);
    return [];
  }
};

// 包装bookmarks API为Promise
const bookmarksGetTree = () => {
  return new Promise((resolve) => {
    chrome.bookmarks.getTree((nodes) => resolve(nodes));
  });
};

const bookmarksMove = (id, destination) => {
  return new Promise((resolve) => {
    chrome.bookmarks.move(id, destination, (result) => resolve(result));
  });
};

const bookmarksCreate = (bookmark) => {
  return new Promise((resolve) => {
    chrome.bookmarks.create(bookmark, (result) => resolve(result));
  });
};

// 合并重复项并归档
const mergeAndArchive = async (duplicates) => {
  try {
    for (const { bookmarks } of duplicates) {
      if (!bookmarks || bookmarks.length === 0) continue;
      
      const keepId = bookmarks[0].id; // 保留最新添加的书签
      if (bookmarks.length > 1) {
        // 移动到归档文件夹
        const archiveFolder = await findOrCreateArchiveFolder();
        
        // 检查归档文件夹是否成功创建
        if (archiveFolder && archiveFolder.id) {
          for (const bookmark of bookmarks.slice(1)) {
            try {
              await bookmarksMove(bookmark.id, { parentId: archiveFolder.id });
              console.log(`Moved bookmark ${bookmark.id} to archive`);
            } catch (error) {
              console.error(`Error moving bookmark ${bookmark.id}:`, error);
            }
          }
        } else {
          console.error('Cannot move bookmarks - archive folder not available');
        }
      }
    }
  } catch (error) {
    console.error('Error in mergeAndArchive:', error);
  }
};

// 查找或创建归档文件夹
const findOrCreateArchiveFolder = async () => {
  try {
    const root = await bookmarksGetTree();
    // 查找现有的归档文件夹
    let archiveFolder = root[0].children?.find(c => c.title === '归档');
    
    if (!archiveFolder) {
      // 查找一个可用的父文件夹（不是根目录）
      // 通常书签栏或其他书签文件夹是安全的父文件夹
      const safeParentFolder = root[0].children?.find(c => 
        c.title === '书签栏' || c.title === 'Bookmarks Bar' || !c.url
      );
      
      if (safeParentFolder) {
        archiveFolder = await bookmarksCreate({
          parentId: safeParentFolder.id,
          title: '归档'
        });
        console.log('Archive folder created successfully');
      } else {
        console.error('No safe parent folder found for archive');
      }
    }
    
    return archiveFolder;
  } catch (error) {
    console.error('Error finding or creating archive folder:', error);
    return null;
  }
};

// 默认分类配置
const DEFAULT_CATEGORIES = {
  '新闻网站': ['news', 'zhihu', 'weibo', '163.com', 'sina.com.cn', 'qq.com', 'ifeng.com'],
  '社交媒体': ['facebook', 'twitter', 'instagram', 'linkedin', 'douban'],
  '视频平台': ['youtube', 'bilibili', 'youku', 'tiktok'],
  '学习资源': ['github', 'wikipedia', 'coursera', 'edX', 'baidu.com'],
  '购物网站': ['taobao', 'tmall', 'jd', 'amazon', 'pdd'],
  '工具网站': ['tool', 'convert', 'calculator', 'validator'],
  '其他网站': []
};

// 从Chrome存储加载分类配置
async function loadCategories() {
  return new Promise((resolve) => {
    chrome.storage.local.get('bookmarkCategories', (result) => {
      // 如果没有保存的配置，返回默认配置
      if (!result.bookmarkCategories || Object.keys(result.bookmarkCategories).length === 0) {
        resolve(JSON.parse(JSON.stringify(DEFAULT_CATEGORIES)));
      } else {
        resolve(result.bookmarkCategories);
      }
    });
  });
}

// 内容分析和自动分类功能 - 增强版（支持词语分析和小类生成）
const analyzeAndCategorizeBookmarks = async (bookmarks) => {
  try {
    if (!bookmarks || !Array.isArray(bookmarks)) {
      console.error('Invalid bookmarks data passed to analyzeAndCategorizeBookmarks');
      return {};
    }
    
    // 加载用户配置的分类规则
    const categoriesConfig = await loadCategories();
    
    // 初始化分类对象（大类）
    const categories = {};
    Object.keys(categoriesConfig).forEach(category => {
      categories[category] = { 
        bookmarks: [],
        subcategories: {} // 用于存储小类
      };
    });
    
    // 1. 首先按大类进行初步分类
    bookmarks.forEach(bookmark => {
      if (bookmark && typeof bookmark === 'object' && bookmark.url) {
        const url = bookmark.url.toLowerCase();
        const title = bookmark.title.toLowerCase();
        let categorized = false;
        
        // 遍历所有分类进行匹配
        Object.entries(categoriesConfig).forEach(([category, keywords]) => {
          // '其他网站'分类最后处理
          if (category === '其他网站') return;
          
          // 检查URL或标题是否包含该分类的任一关键词
          for (const keyword of keywords) {
            if (url.includes(keyword) || title.includes(keyword)) {
              categories[category].bookmarks.push(bookmark);
              categorized = true;
              return false; // 跳出循环，避免一个书签被分到多个分类
            }
          }
        });
        
        // 如果没有匹配到任何分类，放入'其他网站'
        if (!categorized) {
          categories['其他网站'].bookmarks.push(bookmark);
        }
      }
    });
    
    // 2. 对每个大类中的书签进行词语分析，生成小类
    for (const [category, categoryData] of Object.entries(categories)) {
      // 跳过'其他网站'分类和没有书签的分类
      if (category === '其他网站' || categoryData.bookmarks.length === 0) {
        continue;
      }
      
      // 提取所有书签名中的词语并统计词频
      const wordFrequency = {};
      categoryData.bookmarks.forEach(bookmark => {
        if (bookmark && bookmark.title) {
          const words = extractWordsFromTitle(bookmark.title);
          words.forEach(word => {
            if (word && word.length > 1) { // 忽略单个字符的词
              wordFrequency[word] = (wordFrequency[word] || 0) + 1;
            }
          });
        }
      });
      
      // 生成小类（只保留词频较高的词语作为小类名称）
      const subcategories = generateSubcategories(wordFrequency, categoryData.bookmarks);
      categories[category].subcategories = subcategories;
    }
    
    // 对每个分类中的书签按名称排序
    Object.keys(categories).forEach(category => {
      categories[category].bookmarks = sortBookmarksByName(categories[category].bookmarks);
      
      // 对每个小类中的书签也进行排序
      Object.keys(categories[category].subcategories).forEach(subcategory => {
        categories[category].subcategories[subcategory] = sortBookmarksByName(categories[category].subcategories[subcategory]);
      });
    });
    
    return categories;
  } catch (error) {
    console.error('Error in analyzeAndCategorizeBookmarks:', error);
    return {};
  }
};

// 从书签名中提取词语
function extractWordsFromTitle(title) {
  try {
    if (!title || typeof title !== 'string') {
      return [];
    }
    
    // 转换为小写
    title = title.toLowerCase();
    
    // 尝试提取中文字词（简单分词，按字符分割）
    // 实际应用中可以考虑使用更复杂的分词库
    const words = [];
    
    // 提取连续的中文
    let chineseWords = [];
    for (let i = 0; i < title.length; i++) {
      const char = title[i];
      const isChinese = /[\u4e00-\u9fa5]/.test(char);
      
      if (isChinese) {
        chineseWords.push(char);
      } else if (chineseWords.length > 0) {
        // 如果有连续的中文，组合成词
        if (chineseWords.length > 1) {
          words.push(chineseWords.join(''));
        }
        chineseWords = [];
      }
    }
    
    // 处理最后一组中文
    if (chineseWords.length > 1) {
      words.push(chineseWords.join(''));
    }
    
    // 提取英文单词
    const englishMatches = title.match(/[a-z]+/g);
    if (englishMatches) {
      words.push(...englishMatches);
    }
    
    // 过滤掉常见的无意义词语
    const stopWords = ['的', '了', '是', '在', '我', '有', '和', '就', '不', '人', '都', '一', '一个', '上', '也', '很', '到', '说', '要', '去', '你', '会', '着', '没有', '看', '好', '自己', '这'];
    return words.filter(word => !stopWords.includes(word));
  } catch (error) {
    console.error('Error in extractWordsFromTitle:', error);
    return [];
  }
}

// 生成小类
function generateSubcategories(wordFrequency, bookmarks) {
  const subcategories = {};
  const processedBookmarks = new Set();
  
  // 按词频排序，取前N个词作为小类名称
  const sortedWords = Object.entries(wordFrequency)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 10); // 最多生成10个小类
  
  // 为每个高频词创建小类
  sortedWords.forEach(([word, _]) => {
    subcategories[word] = [];
  });
  
  // 将书签分配到小类
  bookmarks.forEach(bookmark => {
    if (!bookmark || !bookmark.title || processedBookmarks.has(bookmark.id)) {
      return;
    }
    
    const title = bookmark.title.toLowerCase();
    let addedToSubcategory = false;
    
    // 检查是否包含小类关键词
    Object.keys(subcategories).forEach(subcategory => {
      if (title.includes(subcategory) && !addedToSubcategory) {
        subcategories[subcategory].push(bookmark);
        processedBookmarks.add(bookmark.id);
        addedToSubcategory = true;
      }
    });
  });
  
  // 过滤掉没有书签的小类
  Object.keys(subcategories).forEach(subcategory => {
    if (subcategories[subcategory].length === 0) {
      delete subcategories[subcategory];
    }
  });
  
  return subcategories;
}

// 按书签名称排序
const sortBookmarksByName = (bookmarks) => {
  try {
    if (!bookmarks || !Array.isArray(bookmarks)) {
      return [];
    }
    
    return bookmarks.sort((a, b) => {
      if (!a || !a.title) return 1;
      if (!b || !b.title) return -1;
      return a.title.localeCompare(b.title, 'zh-CN');
    });
  } catch (error) {
    console.error('Error in sortBookmarksByName:', error);
    return bookmarks || [];
  }
};

// 确保background service worker处于激活状态
const ensureBackgroundWorkerActive = async () => {
  try {
    console.log('开始激活background service worker...');
    
    // 尝试多种方法激活service worker，增加延迟以确保worker完全加载
    const activationPromises = [
      // 方法1: 通过存储API唤醒
      new Promise(resolve => {
        chrome.storage.local.set({ '_ping': Date.now() }, () => {
          console.log('存储API唤醒尝试完成');
          resolve();
        });
      }),
      
      // 方法2: 通过书签API唤醒
      new Promise(resolve => {
        try {
          chrome.bookmarks.getTree(() => {
            console.log('书签API唤醒尝试完成');
            resolve();
          });
        } catch (e) {
          console.log('书签API唤醒失败:', e);
          resolve();
        }
      })
    ];
    
    // 并行执行所有激活方法
    await Promise.all(activationPromises);
    
    // 给足够的时间让service worker完全启动
    await new Promise(r => setTimeout(r, 1000));
    
    // 最后尝试直接ping来确认
    return new Promise(resolve => {
      chrome.runtime.sendMessage({ action: 'ping' }, (response) => {
        if (chrome.runtime.lastError) {
          console.log('ping尝试失败，但service worker可能仍在启动中');
        } else {
          console.log('ping成功，service worker已完全激活');
        }
        resolve();
      });
    });
  } catch (error) {
    console.error('尝试激活service worker时出错:', error);
    return Promise.resolve();
  }
};

// 使用长连接(port)与background service worker通信
const createPortConnection = () => {
  try {
    const port = chrome.runtime.connect({ name: 'bookmark-validator' });
    return port;
  } catch (error) {
    console.error('创建长连接失败:', error);
    return null;
  }
};

// 验证单个URL是否可访问（通过background service worker）
const checkUrlValidity = async (url) => {
  try {
    // 基本URL格式验证
    if (!url || typeof url !== 'string' || !url.startsWith('http')) {
      console.log(`无效的URL格式: ${url}`);
      return false;
    }
    
    // 确保background service worker处于激活状态
    await ensureBackgroundWorkerActive();
    
    // 首先尝试使用长连接方式通信
    const tryPortConnection = (retryCount = 2) => {
      return new Promise((resolve) => {
        const port = createPortConnection();
        
        if (!port) {
          console.log('无法创建长连接，回退到普通消息通信');
          resolve(null); // 表示需要回退到普通消息通信
          return;
        }
        
        // 设置端口消息处理
        port.onMessage.addListener((response) => {
          if (response.url === url) {
            port.disconnect();
            resolve(response);
          }
        });
        
        port.onDisconnect.addListener(() => {
          console.log(`长连接断开 - URL: ${url}`);
          if (retryCount > 0) {
            console.log(`尝试重新创建长连接，剩余重试次数: ${retryCount - 1}`);
            setTimeout(() => {
              tryPortConnection(retryCount - 1).then(resolve);
            }, 1000);
          } else {
            console.log('长连接重试失败，回退到普通消息通信');
            resolve(null);
          }
        });
        
        // 发送验证请求
        try {
          port.postMessage({ action: 'checkUrlValidity', url });
          
          // 设置超时
          setTimeout(() => {
            port.disconnect();
            console.log(`长连接超时 - URL: ${url}`);
            resolve(null);
          }, 8000);
        } catch (error) {
          port.disconnect();
          console.error(`长连接发送消息失败: ${error.message} - URL: ${url}`);
          resolve(null);
        }
      });
    };
    
    // 发送消息到background service worker，支持增强的重试机制
    const sendMessageWithRetry = (message, retryCount = 5, currentDelay = 1000) => {
      return new Promise((resolve) => {
        // 设置一个超时，防止长时间无响应
        const timeoutId = setTimeout(() => {
          console.log(`URL验证超时(15秒): ${url}`);
          resolve({ isValid: false, error: 'timeout' });
        }, 15000); // 增加超时时间到15秒
        
        // 发送消息
        chrome.runtime.sendMessage(message, (response) => {
          clearTimeout(timeoutId); // 清除超时定时器
          
          if (chrome.runtime.lastError) {
            const errorMessage = chrome.runtime.lastError.message;
            console.error(`消息通信错误: ${errorMessage} - URL: ${url}`);
            
            // 如果是连接问题且还有重试次数，进行重试
            if (errorMessage.includes('Receiving end does not exist') && retryCount > 0) {
              console.log(`尝试重新连接background service worker，剩余重试次数: ${retryCount - 1}`);
              // 增加等待时间并在重试前重启激活过程
              setTimeout(() => {
                console.log('在重试前执行完整的service worker重新激活过程');
                
                // 强制重新加载扩展以重置service worker状态
                chrome.runtime.reload();
                
                // 等待扩展重新加载
                setTimeout(async () => {
                  await ensureBackgroundWorkerActive();
                  // 增加下次重试的等待时间
                  const nextDelay = Math.min(currentDelay * 2, 5000); // 最多等待5秒
                  sendMessageWithRetry(message, retryCount - 1, nextDelay).then(resolve);
                }, 2000);
              }, currentDelay);
              return;
            }
            
            resolve({ isValid: false, error: errorMessage });
          } else if (response && response.isValid !== undefined) {
            resolve(response);
          } else {
            console.error(`无效的验证响应:`, response, `- URL: ${url}`);
            resolve({ isValid: false, error: 'invalid_response' });
          }
        });
      });
    };
    
    // 先尝试长连接方式
    let result = await tryPortConnection();
    
    // 如果长连接失败，回退到普通消息通信
    if (result === null) {
      console.log(`长连接方式失败，回退到普通消息通信 - URL: ${url}`);
      result = await sendMessageWithRetry({ action: 'checkUrlValidity', url });
    }
    
    console.log(`URL验证结果 - ${url}: ${result.isValid}`);
    if (!result.isValid && result.error) {
      console.log(`验证失败原因: ${result.error}`);
    }
    
    return result.isValid;
  } catch (error) {
    console.log(`URL验证过程中出错: ${url}`, error.message);
    return false;
  }
};

// 批量验证书签有效性
const validateBookmarks = async (bookmarks) => {
  try {
    if (!bookmarks || !Array.isArray(bookmarks)) {
      console.error('Invalid bookmarks data passed to validateBookmarks');
      return { valid: [], invalid: [] };
    }
    
    const valid = [];
    const invalid = [];
    
    // 限制并发请求数量
    const concurrencyLimit = 5;
    const promises = [];
    
    for (let i = 0; i < bookmarks.length; i++) {
      const bookmark = bookmarks[i];
      if (bookmark && typeof bookmark === 'object' && bookmark.url) {
        
        // 创建一个Promise并立即添加到队列
        const promise = checkUrlValidity(bookmark.url)
          .then(isValid => {
            if (isValid) {
              valid.push(bookmark);
            } else {
              invalid.push(bookmark);
            }
          });
        
        promises.push(promise);
        
        // 控制并发数量
        if (promises.length >= concurrencyLimit) {
          // 等待一组请求完成
          await Promise.all(promises);
          promises.length = 0; // 清空队列
        }
      }
    }
    
    // 等待剩余的请求完成
    if (promises.length > 0) {
      await Promise.all(promises);
    }
    
    // 保存无效书签信息到本地存储，以便后续清除
    if (invalid.length > 0) {
      await chrome.storage.local.set({ invalidBookmarks: invalid });
    }
    
    return { valid, invalid };
  } catch (error) {
    console.error('Error in validateBookmarks:', error);
    return { valid: [], invalid: [] };
  }
};

// 移除无效书签
const removeInvalidBookmarks = async (invalidBookmarks) => {
  try {
    if (!invalidBookmarks || !Array.isArray(invalidBookmarks)) {
      console.error('Invalid invalidBookmarks data passed to removeInvalidBookmarks');
      return 0;
    }
    
    let removedCount = 0;
    
    // 批量删除书签
    for (const bookmark of invalidBookmarks) {
      try {
        await new Promise((resolve, reject) => {
          chrome.bookmarks.remove(bookmark.id, () => {
            if (chrome.runtime.lastError) {
              reject(new Error(chrome.runtime.lastError.message));
            } else {
              resolve();
            }
          });
        });
        removedCount++;
      } catch (error) {
        console.error(`Error removing bookmark ${bookmark.id}:`, error);
      }
    }
    
    // 清除本地存储中的无效书签信息
    await chrome.storage.local.remove('invalidBookmarks');
    
    // 重新加载书签数据
    await new Promise((resolve) => {
      chrome.runtime.sendMessage({ action: 'reloadBookmarks' }, resolve);
    });
    
    return removedCount;
  } catch (error) {
    console.error('Error in removeInvalidBookmarks:', error);
    return 0;
  }
};

document.getElementById('scanBtn').addEventListener('click', async () => {
  try {
    // 显示加载状态
    const resultsElement = document.getElementById('results');
    resultsElement.className = 'message info';
    resultsElement.innerHTML = "<span class='loading'></span>扫描中...";
    
    // 获取书签数据
    const result = await chrome.storage.local.get('bookmarks');
    
    // 检查书签数据是否存在
    if (!result.bookmarks || !Array.isArray(result.bookmarks)) {
      resultsElement.className = 'message error';
      resultsElement.innerHTML = "书签数据未加载完成，请稍后再试。";
      console.error('No bookmarks data found or not in expected format');
      return;
    }
    
    // 查找重复项
    const duplicates = findDuplicates(result.bookmarks);
    
    // 渲染结果
    resultsElement.className = '';
    let html = `<h3>发现 ${duplicates.length} 组重复书签</h3>`;
    
    if (duplicates.length > 0) {
      duplicates.forEach(({ normUrl, bookmarks }) => {
        html += `
          <div class="bookmark-group">
            <div class="bookmark-url">${normUrl}</div>
            ${bookmarks.map(b => `
              <div class="bookmark-item">
                ${b.title} (${new Date(b.dateAdded).toLocaleString()})
              </div>
            `).join('')}
          </div>
        `;
      });
      
      // 自动合并重复项
      await mergeAndArchive(duplicates);
      html += "<div class='message message-success'>已自动归档重复书签</div>";
    } else {
      html += "<div class='message message-info'>未发现重复书签</div>";
    }
    
    resultsElement.innerHTML = html;
  } catch (error) {
    console.error('Error during bookmark scanning:', error);
    const resultsElement = document.getElementById('results');
    resultsElement.className = 'message error';
    resultsElement.innerHTML = "处理书签时发生错误，请刷新页面后重试。";
  }
});

// 添加分析和分类书签按钮事件监听
document.getElementById('analyzeBtn').addEventListener('click', async () => {
  try {
    // 显示加载状态
    const resultsElement = document.getElementById('results');
    resultsElement.className = 'message info';
    resultsElement.innerHTML = "<span class='loading'></span>分析和分类中...";
    
    // 获取书签数据
    const result = await chrome.storage.local.get('bookmarks');
    
    // 检查书签数据是否存在
    if (!result.bookmarks || !Array.isArray(result.bookmarks)) {
      resultsElement.className = 'message error';
      resultsElement.innerHTML = "书签数据未加载完成，请稍后再试。";
      console.error('No bookmarks data found or not in expected format');
      return;
    }
    
    // 分析和分类书签
    const categories = await analyzeAndCategorizeBookmarks(result.bookmarks);
    
    // 渲染分类结果
    resultsElement.className = '';
    let html = '<h3>书签分析和分类结果</h3>';
    
    let hasCategories = false;
    Object.keys(categories).forEach(category => {
      const categoryData = categories[category];
      if (categoryData.bookmarks.length > 0) {
        hasCategories = true;
        html += `
          <div class="category-group">
            <div class="category-title">${category} (${categoryData.bookmarks.length}个)</div>
        `;
        
        // 渲染小类
        const subcategories = categoryData.subcategories;
        if (Object.keys(subcategories).length > 0) {
          html += `
            <div class="subcategories">
          `;
          
          Object.keys(subcategories).forEach(subcategory => {
            html += `
              <div class="subcategory-group">
                <div class="subcategory-title">${subcategory} (${subcategories[subcategory].length}个)</div>
                ${subcategories[subcategory].map(b => `
                  <div class="bookmark-item sub-item">
                    ${b.title}
                  </div>
                `).join('')}
              </div>
            `;
          });
          
          html += `
            </div>
          `;
        }
        
        // 渲染未分配到小类的书签
        const uncategorizedInCategory = categoryData.bookmarks.filter(b => {
          // 检查书签是否在任何小类中
          for (const subcategory of Object.values(subcategories)) {
            if (subcategory.some(sb => sb.id === b.id)) {
              return false;
            }
          }
          return true;
        });
        
        if (uncategorizedInCategory.length > 0) {
          html += `
            <div class="uncategorized">
              <div class="subcategory-title">其他 (${uncategorizedInCategory.length}个)</div>
              ${uncategorizedInCategory.map(b => `
                <div class="bookmark-item">
                  ${b.title}
                </div>
              `).join('')}
            </div>
          `;
        }
        
        html += `
          </div>
        `;
      }
    });
    
    if (!hasCategories) {
      html += "<div class='message message-info'>没有可分析的书签数据</div>";
    } else {
      // 添加自动分类按钮
      html += "<button id='autoCategorizeBtn' class='btn btn-primary'>自动分类并创建收藏夹</button>";
    }
    
    resultsElement.innerHTML = html;
    
    // 为自动分类按钮添加事件监听
    if (hasCategories) {
      document.getElementById('autoCategorizeBtn').addEventListener('click', async () => {
        try {
          // 显示加载状态
          const autoCategorizeBtn = document.getElementById('autoCategorizeBtn');
          autoCategorizeBtn.disabled = true;
          autoCategorizeBtn.innerHTML = "<span class='loading'></span>分类中...";
          
          // 执行自动分类操作
          const categorizedCount = await performAutoCategorization(categories);
          
          // 显示结果
          autoCategorizeBtn.innerHTML = "分类完成";
          resultsElement.insertAdjacentHTML('beforeend', 
            `<div class='message message-success'>成功分类 ${categorizedCount} 个书签</div>`);
          
          // 重新加载书签数据
          await new Promise((resolve) => {
            chrome.runtime.sendMessage({ action: 'reloadBookmarks' }, resolve);
          });
        } catch (error) {
          console.error('Error during auto-categorization:', error);
          resultsElement.insertAdjacentHTML('beforeend', 
            `<div class='message error'>分类过程中发生错误：${error.message}</div>`);
        }
      });
    }
  } catch (error) {
    console.error('Error during bookmark analysis:', error);
    const resultsElement = document.getElementById('results');
    resultsElement.className = 'message error';
    resultsElement.innerHTML = "分析书签时发生错误，请刷新页面后重试。";
  }
});

// 添加验证书签有效性按钮事件监听
document.getElementById('validateBtn').addEventListener('click', async () => {
  try {
    // 显示加载状态
    const resultsElement = document.getElementById('results');
    resultsElement.className = 'message info';
    resultsElement.innerHTML = "<span class='loading'></span>正在校验书签有效性...这可能需要一些时间";
    
    // 获取书签数据
    const result = await chrome.storage.local.get('bookmarks');
    
    // 检查书签数据是否存在
    if (!result.bookmarks || !Array.isArray(result.bookmarks)) {
      resultsElement.className = 'message error';
      resultsElement.innerHTML = "书签数据未加载完成，请稍后再试。";
      console.error('No bookmarks data found or not in expected format');
      return;
    }
    
    // 验证书签有效性
    const { valid, invalid } = await validateBookmarks(result.bookmarks);
    
    // 更新清除无效书签按钮状态
    const removeInvalidBtn = document.getElementById('removeInvalidBtn');
    if (invalid.length > 0) {
      removeInvalidBtn.disabled = false;
    } else {
      removeInvalidBtn.disabled = true;
    }
    
    // 渲染验证结果
    resultsElement.className = '';
    let html = `<h3>书签有效性校验结果</h3>`;
    
    html += `<div class='message message-success'>有效书签：${valid.length}个</div>`;
    
    if (invalid.length > 0) {
      html += `
        <h4>无效书签（${invalid.length}个）</h4>
        ${invalid.map(b => `
          <div class="invalid-bookmark">
            <div class="title">${b.title}</div>
            <div class="url">${b.url}</div>
          </div>
        `).join('')}
        <div class='message message-info'>建议清除无效书签以保持书签整洁</div>
      `;
    } else {
      html += "<div class='message message-success'>恭喜！所有书签都有效</div>";
    }
    
    resultsElement.innerHTML = html;
  } catch (error) {
    console.error('Error during bookmark validation:', error);
    const resultsElement = document.getElementById('results');
    resultsElement.className = 'message error';
    resultsElement.innerHTML = "验证书签时发生错误，请刷新页面后重试。";
  }
});

// 添加配置分类按钮事件监听
document.getElementById('configBtn').addEventListener('click', () => {
  // 打开配置页面
  chrome.runtime.openOptionsPage();
});

// 自动分类功能 - 增强版（支持多级分类文件夹）
async function performAutoCategorization(categories) {
  let totalCategorized = 0;
  
  // 遍历所有大类
  for (const [category, categoryData] of Object.entries(categories)) {
    const bookmarks = categoryData.bookmarks;
    if (bookmarks.length === 0) continue;
    
    try {
      // 查找或创建大类文件夹
      const categoryFolder = await findOrCreateCategoryFolder(category);
      
      // 跟踪已移动的书签ID
      const movedBookmarkIds = new Set();
      
      // 1. 处理小类
      const subcategories = categoryData.subcategories;
      if (Object.keys(subcategories).length > 0) {
        for (const [subcategory, subBookmarks] of Object.entries(subcategories)) {
          try {
            // 在大类文件夹下创建小类文件夹
            const subcategoryFolder = await findOrCreateSubcategoryFolder(subcategory, categoryFolder.id);
            
            // 移动书签到小类文件夹
            for (const bookmark of subBookmarks) {
              await bookmarksMove(bookmark.id, { parentId: subcategoryFolder.id });
              movedBookmarkIds.add(bookmark.id);
              totalCategorized++;
            }
          } catch (subError) {
            console.error(`Error creating subcategory ${subcategory} for ${category}:`, subError);
            // 继续处理其他小类
          }
        }
      }
      
      // 2. 处理未分配到小类的书签
      const uncategorizedBookmarks = bookmarks.filter(bookmark => 
        !movedBookmarkIds.has(bookmark.id)
      );
      
      for (const bookmark of uncategorizedBookmarks) {
        // 将未分类书签移动到大类文件夹
        await bookmarksMove(bookmark.id, { parentId: categoryFolder.id });
        totalCategorized++;
      }
      
    } catch (error) {
      console.error(`Error categorizing bookmarks for ${category}:`, error);
      // 继续处理其他分类，不中断整个流程
    }
  }
  
  return totalCategorized;
}

// 查找或创建小类文件夹
async function findOrCreateSubcategoryFolder(subcategoryName, parentFolderId) {
  try {
    // 获取父文件夹下的所有子项
    const parentFolder = await new Promise((resolve, reject) => {
      chrome.bookmarks.get(parentFolderId, (results) => {
        if (chrome.runtime.lastError) {
          reject(new Error(chrome.runtime.lastError.message));
        } else {
          resolve(results && results[0] ? results[0] : null);
        }
      });
    });
    
    if (!parentFolder || !parentFolder.children) {
      throw new Error('父文件夹无效');
    }
    
    // 查找是否已存在同名小类文件夹
    const existingFolder = parentFolder.children.find(item => 
      item && item.title === subcategoryName && item.type === 'folder'
    );
    
    if (existingFolder) {
      return existingFolder;
    }
    
    // 如果不存在，则创建新文件夹
    return await bookmarksCreate({
      parentId: parentFolderId,
      title: subcategoryName,
      type: 'folder'
    });
  } catch (error) {
    console.error(`Error finding or creating subcategory folder ${subcategoryName}:`, error);
    throw new Error(`无法创建或找到子分类文件夹: ${error.message}`);
  }
}

// 查找或创建分类文件夹
async function findOrCreateCategoryFolder(categoryName) {
  try {
    // 首先获取整个书签树
    const bookmarkTree = await bookmarksGetTree();
    
    // 提取根目录的子项（书签树的第一个元素是根目录）
    if (!bookmarkTree || !bookmarkTree[0] || !bookmarkTree[0].children) {
      throw new Error('书签树结构无效');
    }
    
    const rootChildren = bookmarkTree[0].children;
    
    // 在根目录查找是否已存在同名文件夹
    const existingFolder = rootChildren.find(item => 
      item && item.title === categoryName && item.type === 'folder'
    );
    
    if (existingFolder) {
      return existingFolder;
    }
    
    // 如果不存在，则创建新文件夹
    return await bookmarksCreate({
      parentId: '1', // 根目录
      title: categoryName,
      type: 'folder'
    });
  } catch (error) {
    console.error(`Error finding or creating category folder ${categoryName}:`, error);
    throw new Error(`无法创建或找到分类文件夹: ${error.message}`);
  }
}

// 添加一键清除无效书签按钮事件监听
document.getElementById('removeInvalidBtn').addEventListener('click', async () => {
  try {
    // 确认清除
    if (!confirm('确定要删除所有无效书签吗？此操作不可撤销。')) {
      return;
    }
    
    // 显示加载状态
    const resultsElement = document.getElementById('results');
    resultsElement.className = 'message info';
    resultsElement.innerHTML = "<span class='loading'></span>正在清除无效书签...";
    
    // 获取无效书签
    const result = await chrome.storage.local.get('invalidBookmarks');
    
    if (!result.invalidBookmarks || !Array.isArray(result.invalidBookmarks) || result.invalidBookmarks.length === 0) {
      resultsElement.className = 'message error';
      resultsElement.innerHTML = "没有需要清除的无效书签";
      return;
    }
    
    // 移除无效书签
    const removedCount = await removeInvalidBookmarks(result.invalidBookmarks);
    
    // 更新清除无效书签按钮状态
    document.getElementById('removeInvalidBtn').disabled = true;
    
    // 显示清除结果
    resultsElement.className = '';
    let html = `<div class='message message-success'>成功清除 ${removedCount} 个无效书签</div>`;
    
    if (removedCount < result.invalidBookmarks.length) {
      html += `<div class='message message-info'>部分书签可能无法删除，请刷新页面后再次尝试</div>`;
    }
    
    resultsElement.innerHTML = html;
  } catch (error) {
    console.error('Error during bookmark removal:', error);
    const resultsElement = document.getElementById('results');
    resultsElement.className = 'message error';
    resultsElement.innerHTML = "清除书签时发生错误，请刷新页面后重试。";
  }
});